package com.yzt.message;

import static com.yzt.message.MessageConstants.TYPE_ACCOUNT_NOTICE_FENS;
import static com.yzt.message.MessageConstants.TYPE_ACCOUNT_SYSTEM;
import static com.yzt.message.MessageConstants.TYPE_INTERACTIVE_MESSAGE;

import android.app.Application;
import android.app.NotificationChannel;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.lifecycle.MutableLiveData;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.yzt.message.custom.RXCreateGroupContent;
import com.yzt.message.custom.RXCreateGroupMessageItemProvider;
import com.yzt.message.custom.RXGameContent;
import com.yzt.zhuju.message.RXGameMessageContent;
import com.yzt.message.custom.RXGroupEditContent;
import com.yzt.message.custom.RXGroupEditMessageItemProvider;
import com.yzt.message.custom.RXGroupJoinContent;
import com.yzt.message.custom.RXGroupJoinMessageItemProvider;
import com.yzt.message.custom.RXGroupKickContent;
import com.yzt.message.custom.RXGroupKickMessageItemProvider;
import com.yzt.message.custom.RXGroupQuitContent;
import com.yzt.message.custom.RXGroupQuitMessageItemProvider;
import com.yzt.message.custom.RXJoinGameContent;
import com.yzt.message.custom.RXRedPkgMessageContent;
import com.yzt.message.custom.RXRedPkgMessageItemProvider;
import com.yzt.message.custom.RXShareMessageContent;
import com.yzt.message.custom.RXShareMessageItemProvider;
import com.yzt.message.custom.RedPackageTipMessageContent;
import com.yzt.message.custom.RedPackageTipMessageItemProvider;
import com.yzt.zhuju.IService.chatroom.ChatRoomMsgType;
import com.yzt.zhuju.MainMenuContsant;
import com.yzt.zhuju.RXingUtils;
import com.yzt.zhuju.arouter.RouterMain;
import com.yzt.zhuju.arouter.RouterMessage;
import com.yzt.zhuju.arouter.RouterUser;
import com.yzt.zhuju.config.AppConfigCacheManager;
import com.yzt.zhuju.config.AppKeyConfig;
import com.yzt.zhuju.event.RxBus;
import com.yzt.zhuju.event.call.AgoraCallEvent;
import com.yzt.zhuju.event.im.RongYunExceptionEvent;
import com.yzt.zhuju.event.im.RongYunLoginSuccessEvent;
import com.yzt.zhuju.event.im.RongYunMessageChangeEvent;
import com.yzt.zhuju.event.im.RongYunMessageUnreadStatusEvent;
import com.yzt.zhuju.event.main.ExitAppEvent;
import com.yzt.zhuju.event.main.MessageListRefreshEvent;
import com.yzt.zhuju.event.message.CustomAttachEvent;
import com.yzt.zhuju.manager.RongYunOnReceiverMsgManager;
import com.yzt.zhuju.network.AresSubscriber;
import com.yzt.zhuju.network.HttpUrlManager;
import com.yzt.zhuju.network.biz.BizLayer;
import com.yzt.zhuju.network.entity.call.AgoraCallMsg;
import com.yzt.zhuju.network.entity.chatroom.BroadCastType;
import com.yzt.zhuju.network.entity.chatroom.ChatRoomGiftDetail;
import com.yzt.zhuju.network.entity.chatroom.GiftIconEvent;
import com.yzt.zhuju.network.entity.chatroom.ShowGiftFullScreenAnimEvent;
import com.yzt.zhuju.network.entity.message.CompanyNoticeData;
import com.yzt.zhuju.network.entity.sysConfig.SystemConfigBean;
import com.yzt.zhuju.network.entity.user.UserLoginInfo;
import com.yzt.zhuju.network.im.InterceptMsg;
import com.yzt.zhuju.rongyun.ChatRoomMessage;
import com.yzt.zhuju.rongyun.IMMessageType;
import com.yzt.zhuju.utils.ActivityManagerUtils;
import com.yzt.zhuju.utils.PreferencesUtils;
import com.yzt.zhuju.utils.TimeUtils;
import com.yzt.zhuju.utils.ViewUtil;
import com.yzt.p_base.utils.LogDataUtils;
import com.yzt.p_base.utils.TLogManager;
import com.yzt.p_base.utils.ToastUtil;
import com.yzt.plugin_imageloader.ImageLoadUtil;
import com.yzt.message.custom.RXDiceMessageContent;
import com.yzt.message.custom.RXDiceMessageItemProvider;
import com.yzt.message.custom.RXGiftMessageContent;
import com.yzt.message.custom.ChatRoomMessageContent;
import com.yzt.message.custom.RXChatRoomNoticeFensContent;
import com.yzt.message.custom.RXInformationNotificationMessageItemProvider;
import com.yzt.message.custom.RXOfficeNoticeMessageContent;
import com.yzt.message.custom.RXSystemPublishContent;
import com.yzt.message.activity.ConversationActivity;
import com.yzt.message.activity.SystemMessageActivity;
import com.yzt.message.conversation.CustomConversationReceiptHandler;
import com.yzt.message.conversation.ReceiptHandlerContainer;
import com.yzt.message.conversation.SystemConversationReceiptHandler;
import com.yzt.message.custom.BroadcastMessageContent;
import com.yzt.message.custom.CustomConversationProvider;
import com.yzt.message.custom.CustomGIFMessageItemProvider;
import com.yzt.message.custom.CustomImageMessageItemProvider;
import com.yzt.message.custom.CustomTextMessageItemProvider;
import com.yzt.message.custom.RXChatRoomGiftContent;
import com.yzt.message.custom.RXCustomTipMessageContent;
import com.yzt.message.custom.RXCustomTipMessageItemProvider;
import com.yzt.message.custom.RXGiftMessageItemProvider;
import com.yzt.message.custom.RXLongTipMessageContent;
import com.yzt.message.custom.RXShowTipMessageContent;
import com.yzt.message.custom.RXShowTipMessageItemProvider;
import com.yzt.message.custom.RxAgoraCallMessageContent;
import com.yzt.message.custom.RxAgoraCallMessageProvider;
import com.yzt.message.custom.RxHQVoiceMessageItemProvider;
import com.yzt.message.msgdialog.MsgFloatDialogHelper;
import com.yzt.message.util.MessageInfoUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import io.rong.common.RLog;
import io.rong.imkit.GlideKitImageEngine;
import io.rong.imkit.IMCenter;
import io.rong.imkit.MessageInterceptor;
import io.rong.imkit.RongIM;
import io.rong.imkit.config.BaseDataProcessor;
import io.rong.imkit.config.ConversationClickListener;
import io.rong.imkit.config.ConversationListBehaviorListener;
import io.rong.imkit.config.RongConfigCenter;
import io.rong.imkit.conversation.extension.RongExtensionManager;
import io.rong.imkit.conversation.messgelist.provider.GIFMessageItemProvider;
import io.rong.imkit.conversation.messgelist.provider.HQVoiceMessageItemProvider;
import io.rong.imkit.conversation.messgelist.provider.ImageMessageItemProvider;
import io.rong.imkit.conversation.messgelist.provider.InformationNotificationMessageItemProvider;
import io.rong.imkit.conversation.messgelist.provider.TextMessageItemProvider;
import io.rong.imkit.conversationlist.model.BaseUiConversation;
import io.rong.imkit.conversationlist.model.GatheredConversation;
import io.rong.imkit.conversationlist.model.SingleConversation;
import io.rong.imkit.conversationlist.provider.PrivateConversationProvider;
import io.rong.imkit.feature.mention.IExtensionEventWatcher;
import io.rong.imkit.notification.DefaultInterceptor;
import io.rong.imkit.userinfo.RongUserInfoManager;
import io.rong.imkit.utils.RouteUtils;
import io.rong.imkit.widget.adapter.IViewProvider;
import io.rong.imkit.widget.adapter.IViewProviderListener;
import io.rong.imkit.widget.adapter.ProviderManager;
import io.rong.imkit.widget.adapter.ViewHolder;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.MentionedInfo;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.imlib.model.UserInfo;
import io.rong.message.HQVoiceMessage;
import io.rong.message.ImageMessage;
import io.rong.message.InformationNotificationMessage;
import io.rong.message.TextMessage;
import io.rong.push.PushEventListener;
import io.rong.push.PushType;
import io.rong.push.RongPushClient;
import io.rong.push.notification.PushNotificationMessage;
import io.rong.push.pushconfig.PushConfig;

/**
 * 聊天管理器
 */
public class IMManager {

    private static final String TAG_MODULE = "LoginInit";

    private static final String TAG_MODULE1 = "1V1ChatCall";

    private static final String TAG = IMManager.class.getSimpleName();

    private static volatile IMManager mInstance;

    private Context context;

    private final MutableLiveData<Boolean> autoLoginResult = new MutableLiveData<>();

    public static IMManager getInstance() {
        if (mInstance == null) {
            synchronized (IMManager.class) {
                if (mInstance == null) {
                    mInstance = new IMManager();
                }
            }
        }
        return mInstance;
    }

    /**
     * @param application application
     */
    public void init(Application application) {

        this.context = application.getApplicationContext();

        // 初始化推送
        //initPush();

        //初始化一些必须在融云init之前的操作
        initConfigureBefore();

        // 调用 RongIM 初始化
        initRongIM(application);

        //初始化拦截器
        initInterceptor();

        //IM 配置
        initIMConfig();

        // 初始化用户和群组信息内容提供者
        initInfoProvider(context);

        // 初始化自定义消息和消息模版
        initMessageAndTemplate();

        // 初始化连接状态变化监听
        initConnectStateChangeListener();

        // 初始化消息监听
        initOnReceiveMessage(context);

        // 融云登录
        cacheConnectIM();

        RongExtensionManager.getInstance().addExtensionEventWatcher(new IExtensionEventWatcher() {
            @Override
            public void onTextChanged(Context context, Conversation.ConversationType type, String targetId, int cursorPos, int count, String text) {

            }

            @Override
            public void onSendToggleClick(Message message) {
                if (message != null &&
                        message.getContent() != null &&
                        message.getContent().getMentionedInfo() != null &&
                        message.getContent().getMentionedInfo().getMentionedUserIdList() != null &&
                        message.getContent().getMentionedInfo().getMentionedUserIdList().size() > 0 &&
                        message.getContent().getMentionedInfo().getMentionedUserIdList().get(0).equals(String.valueOf(-1))) {
                    message.getContent().getMentionedInfo().setType(MentionedInfo.MentionedType.ALL);
                }
            }

            @Override
            public void onDeleteClick(Conversation.ConversationType type, String targetId, EditText editText, int cursorPos) {

            }

            @Override
            public void onDestroy(Conversation.ConversationType type, String targetId) {

            }
        });
    }

    /**
     * 初始化配置在融云sdk之前
     */
    private void initConfigureBefore() {
        //处理消息中的用户信息，如果这里不移除，会造成用户信息的再次插入数据库，从而刷新列表
        IMCenter.getInstance().addOnReceiveMessageListener(new RongIMClient.OnReceiveMessageWrapperListener() {
            @Override
            public boolean onReceived(Message message, int i, boolean b, boolean b1) {
                if (message != null && message.getContent() != null && message.getContent().getUserInfo() != null) {
                    UserInfo messageUserInfo = message.getContent().getUserInfo();
                    UserInfo userInfo = RongUserInfoManager.getInstance().getUserInfo(message.getTargetId());
                    if (messageUserInfo != null) {
                        if (!userInfoChange(messageUserInfo, userInfo)) {
                            if (messageUserInfo.getName() == null) {
                                messageUserInfo.setName("");
                            }
                            String url = ImageLoadUtil.url2webp(messageUserInfo.getPortraitUri().toString(), 150);
                            messageUserInfo.setPortraitUri(Uri.parse(url));
                            RongUserInfoManager.getInstance().refreshUserInfoCache(messageUserInfo);
                        }
                        message.getContent().setUserInfo(null);
                    }

                }
                return false;
            }
        });
    }

    private boolean userInfoChange(UserInfo messageUserInfo, UserInfo userInfo) {

        if (messageUserInfo == null || userInfo == null) {
            return false;
        }

        try {
            String aa = messageUserInfo.getUserId() + "__" + messageUserInfo.getPortraitUri() + "__" + messageUserInfo.getExtra();
            String bb = userInfo.getUserId() + "__" + userInfo.getPortraitUri() + "__" + userInfo.getExtra();
            return TextUtils.equals(aa, bb);
        } catch (Exception ignored) {

        }

        return false;
    }

    /**
     * 初始化推送
     */
    private void initPush() {
        /*
         * 配置 融云 IM 消息推送
         * 根据需求配置各个平台的推送
         * 配置推送需要在初始化 融云 SDK 之前
         */
        PushConfig config = new PushConfig
                .Builder()
                .enableFCM(true)
                .build();
        RongPushClient.setPushConfig(config);

        RongPushClient.setPushEventListener(new PushEventListener() {
            @Override
            public boolean preNotificationMessageArrived(Context context, PushType pushType, PushNotificationMessage notificationMessage) {
                RLog.d(TAG, "preNotificationMessageArrived");

                String targetId = notificationMessage.getTargetId();
                try {
                    if (!"2".equals(targetId) && Integer.parseInt(targetId) <= 1000) {
                        return false;
                    }
                } catch (Exception e) {
                    return false;
                }
                return true;
            }

            @Override
            public void afterNotificationMessageArrived(Context context, PushType pushType, PushNotificationMessage notificationMessage) {

            }

            @Override
            public boolean onNotificationMessageClicked(Context context, PushType pushType, PushNotificationMessage notificationMessage) {
                if (RXingUtils.getLoginAccount() != null && RXingUtils.getLoginAccount().getUserInfo() != null) {
                    if (RXingUtils.getLoginAccount().getUserInfo().getGender() == 0) {
                        return true;
                    }
                }

                String targetId = notificationMessage.getTargetId();

                if (MessageInfoUtil.isNeedFilter(targetId)) {
                    RouterMain.MainActivity();
                    return true;
                }

                return false;
            }

            @Override
            public void onThirdPartyPushState(PushType pushType, String action, long resultCode) {

            }
        });

        RongConfigCenter.notificationConfig().setInterceptor(new DefaultInterceptor() {
            @Override
            public boolean isNotificationIntercepted(Message message) {

                try {
                    String targetId = message.getTargetId();
                    if (!"2".equals(targetId) && Integer.parseInt(targetId) <= 1000) {
                        return true;
                    } else {
                        boolean flag = PreferencesUtils.isShowMessageDetail();
                        message.getMessagePushConfig().setForceShowDetailContent(flag);
                    }
                } catch (Exception e) {
                    return true;
                }

                return super.isNotificationIntercepted(message);
            }

            @Override
            public boolean isHighPriorityMessage(Message message) {
                //通知修改优先级  免打扰消息逻辑更改
                return false;
            }

            @Override
            public NotificationChannel onRegisterChannel(NotificationChannel defaultChannel) {
                return super.onRegisterChannel(defaultChannel);
            }

            /**
             * 设置本地通知 PendingIntent 时的回调。
             * 应用层可通过此方法更改 PendingIntent 里的设置，以便自定义本地通知的点击行为。
             * 点击本地通知时，SDK 默认跳转到对应会话页面。
             * @param pendingIntent SDK 默认 PendingIntent
             * @param intent        pendingIntent 里携带的 intent。
             *                      可通过 intent 获取以下信息:
             *                      intent.getStringExtra(RouteUtils.CONVERSATION_TYPE);
             *                      intent.getStringExtra(RouteUtils.TARGET_ID);
             *                      intent.getIntExtra(RouteUtils.MESSAGE_ID, -1);;
             * @return 本地通知里需配置的 PendingIntent.
             */
            @Override
            public PendingIntent onPendingIntent(PendingIntent pendingIntent, Intent intent) {

                if (RXingUtils.getLoginAccount() != null && RXingUtils.getLoginAccount().getUserInfo() != null) {
                    if (RXingUtils.getLoginAccount().getUserInfo().getGender() == 0) {
                        return null;
                    }
                }

                String targetId = intent.getStringExtra(RouteUtils.TARGET_ID);

                Intent intentNew = new Intent(context, ConversationActivity.class); //自定义跳转到会话列表
                intentNew.putExtra("im_targetId", targetId);

                if (MessageInfoUtil.isNeedFilter(targetId)) {
                    intentNew = new Intent(context, SystemMessageActivity.class); //自定义跳转到会话列表
                    intentNew.putExtra("im_targetId", targetId);
                }

                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
                    return PendingIntent.getActivity(context, Integer.parseInt(targetId), intentNew, PendingIntent.FLAG_IMMUTABLE);
                } else {
                    return PendingIntent.getActivity(context, Integer.parseInt(targetId), intentNew, PendingIntent.FLAG_ONE_SHOT);
                }
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void openFlowWidowPermissionActivity(Context context) {
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + context.getPackageName()));
        context.startActivity(intent);
    }

    /**
     * 调用初始化 RongIM
     */
    private void initRongIM(Application application) {
        /*
         * 如果是连接到私有云需要在此配置服务器地址
         * 如果是公有云则不需要调用此方法
         */
        setServerInfo("navsg01.cn.ronghub.com", null);
        if (HttpUrlManager.getEnvironment() > 1) {
            //默认测试环境
            IMCenter.init(application, AppKeyConfig.RONG_ID_DEBUG, true);
        } else {
            IMCenter.init(application, AppKeyConfig.RONG_ID_RELEASE, true);
        }
    }

    public static void setServerInfo(final String naviServer, final String fileServer) {
        if (TextUtils.isEmpty(naviServer)) {
            RLog.e(TAG, "setServerInfo naviServer should not be null.");
            throw new IllegalArgumentException("naviServer should not be null.");
        }
        RongIMClient.setServerInfo(naviServer, fileServer);
    }

    /**
     * 消息拦截器
     */
    private void initInterceptor() {
        IMCenter.getInstance().setMessageInterceptor(new MessageInterceptor() {
            @Override
            public boolean interceptReceivedMessage(Message message, int left, boolean hasPackage, boolean offline) {
                try {
                    if (message.getConversationType() == Conversation.ConversationType.SYSTEM && !TextUtils.equals(message.getSenderUserId(), "20")) {
                        return true;
                    }
                    if (message.getTargetId().equals(MessageConstants.TYPE_PUSH_NOTICE)) {
                        return false;
                    }
                    if (message.getObjectName().equals(IMMessageType.BROAD_CAST_MESSAGE)) {
                        MessageContent messageContent = message.getContent();
                        BroadcastMessageContent mBroadcastMessageContent = (BroadcastMessageContent) (messageContent);
                        CompanyNoticeData mCompanyNoticeData = JSON.parseObject(mBroadcastMessageContent.getExtra(), CompanyNoticeData.class);
                        if (mCompanyNoticeData != null && mCompanyNoticeData.getType() != null) {
                            return false;
                        }
                    } else if (message.getObjectName().equals(IMMessageType.TYPE_CHAT_ROOM_NOTICE_FENS_MSG)) {
                        RongIMClient.getInstance().getLatestMessages(Conversation.ConversationType.PRIVATE, TYPE_ACCOUNT_NOTICE_FENS, 1000,
                                new RongIMClient.ResultCallback<List<Message>>() {
                                    @Override
                                    public void onSuccess(List<Message> messages) {
                                        if (messages != null && messages.size() > 0) {
                                            int[] messageIds = new int[messages.size()];
                                            for (int index = 0; index < messages.size(); index++) {
                                                messageIds[index] = messages.get(index).getMessageId();
                                            }
                                            RongIMClient.getInstance().deleteMessages(messageIds, new RongIMClient.ResultCallback<Boolean>() {
                                                @Override
                                                public void onSuccess(Boolean aBoolean) {
                                                    LogDataUtils.d("rongyun_message", "删除数据成功 onSuccess: " + messageIds);
                                                }

                                                @Override
                                                public void onError(RongIMClient.ErrorCode errorCode) {
                                                    LogDataUtils.d("rongyun_message", "删除数据失败 onError: " + errorCode);
                                                }
                                            });
                                        }
                                    }

                                    @Override
                                    public void onError(RongIMClient.ErrorCode errorCode) {

                                    }
                                });
                        return true;
                    } else if (MainMenuContsant.isLimitConsumption() && message.getObjectName().equals(IMMessageType.TIP_CUSTOM_MSG)) {
                        return true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            public boolean interceptOnSendMessage(Message message) {
                return false;
            }

            @Override
            public boolean interceptOnSentMessage(Message message) {
                return false;
            }

            @Override
            public boolean interceptOnInsertOutgoingMessage(Conversation.ConversationType type, String targetId, Message.SentStatus sentStatus, MessageContent content, long time) {
                return false;
            }

            @Override
            public boolean interceptOnInsertIncomingMessage(Conversation.ConversationType type, String targetId, String senderId, Message.ReceivedStatus receivedStatus, MessageContent content, long time) {
                return false;
            }
        });
    }

    private void loadNormalData() {
        UserInfo systemCenter1 = new UserInfo(TYPE_INTERACTIVE_MESSAGE, context.getString(R.string.interactive_notice), Uri.parse(""));
        RongIM.getInstance().refreshUserInfoCache(systemCenter1);
        UserInfo systemCenter = new UserInfo(TYPE_ACCOUNT_SYSTEM, context.getString(R.string.office_notice), Uri.parse(""));
        RongIM.getInstance().refreshUserInfoCache(systemCenter);
    }

    /**
     * IM 配置
     */
    private void initIMConfig() {

        loadNormalData();

        // 将私聊，群组加入消息已读回执
        Conversation.ConversationType[] types = new Conversation.ConversationType[]{
                Conversation.ConversationType.PRIVATE,
                Conversation.ConversationType.GROUP,
                Conversation.ConversationType.ENCRYPTED
        };

        //开启消息已读回执
        RongConfigCenter.featureConfig().enableReadReceipt(types);

        // 配置会话列表界面相关内容
        initConversationList();

        //配置会话界面
        initConversation();

        //开启阅后即焚
        RongConfigCenter.featureConfig().enableDestruct(false);

        RongConfigCenter.featureConfig().setPreLoadUserCache(true);

        RongConfigCenter.featureConfig().setUserCacheMaxCount(1000);

        //开启多选
//        RongConfigCenter.conversationConfig().setShowMoreClickAction(false);
//        RongConfigCenter.conversationConfig().addMoreClickAction();//多选菜单添加

        //设置声音质量
        RongIM.getInstance().setVoiceMessageType(IMCenter.VoiceMessageType.HighQuality);

        //设置加载图片圆角
        RongConfigCenter.featureConfig().setKitImageEngine(new GlideKitImageEngine() {
            @Override
            public void loadConversationListPortrait(@NonNull Context context, @NonNull String url, @NonNull ImageView imageView, Conversation conversation) {
                @DrawableRes int resourceId = R.mipmap.icon_placeholder;
                switch (conversation.getConversationType()) {
                    case GROUP:
                        resourceId = io.rong.imkit.R.drawable.rc_default_group_portrait;
                        break;
                    case CUSTOMER_SERVICE:
                        resourceId = io.rong.imkit.R.drawable.rc_cs_default_portrait;
                        break;
                    case CHATROOM:
                        resourceId = io.rong.imkit.R.drawable.rc_default_chatroom_portrait;
                        break;
                }

                Glide.with(imageView).load(url)
                        .placeholder(resourceId)
                        .error(resourceId)
                        .into(imageView);
            }

            @Override
            public void loadConversationPortrait(@NonNull Context context, @NonNull String url, @NonNull ImageView imageView, Message message) {
                @DrawableRes int resourceId = R.mipmap.icon_placeholder;
                if (message.getConversationType() == Conversation.ConversationType.CUSTOMER_SERVICE) {
                    if (Message.MessageDirection.RECEIVE == message.getMessageDirection()) {
                        resourceId = io.rong.imkit.R.drawable.rc_cs_default_portrait;
                    }
                }
                Glide.with(imageView).load(url)
                        .placeholder(resourceId)
                        .error(resourceId)
                        .into(imageView);
            }
        });
    }

    /**
     * 初始化信息提供者，包括用户信息，群组信息，群主成员信息
     */
    private void initInfoProvider(Context context) {
        IMInfoProvider imInfoProvider = new IMInfoProvider();
        imInfoProvider.init(context);
    }

    /**
     * 初始化会话列表相关事件
     */
    private void initConversationList() {
        Conversation.ConversationType[] supportedTypes = {
                Conversation.ConversationType.PRIVATE,
                Conversation.ConversationType.DISCUSSION,
                Conversation.ConversationType.GROUP,
                Conversation.ConversationType.CHATROOM,
                Conversation.ConversationType.CUSTOMER_SERVICE,
                Conversation.ConversationType.SYSTEM,
                Conversation.ConversationType.APP_PUBLIC_SERVICE,
                Conversation.ConversationType.PUBLIC_SERVICE,
                Conversation.ConversationType.PUSH_SERVICE,
                Conversation.ConversationType.ENCRYPTED,
                Conversation.ConversationType.RTC_ROOM,
//                PRIVATE(1, "private"),
//                DISCUSSION(2, "discussion"),
//                GROUP(3, "group"),
//                CHATROOM(4, "chatroom"),
//                CUSTOMER_SERVICE(5, "customer_service"),
//                SYSTEM(6, "system"),
//                APP_PUBLIC_SERVICE(7, "app_public_service"),
//                PUBLIC_SERVICE(8, "public_service"),
//                PUSH_SERVICE(9, "push_service"),
//                ENCRYPTED(11, "encrypted"),
//                RTC_ROOM(12, "rtc_room");
        };

        //自定义业务过滤器
        ReceiptHandlerContainer.mContext = this.context;
        ReceiptHandlerContainer.getInstance().removeAll();
        ReceiptHandlerContainer.getInstance().registerMessageReceiptHandler(new SystemConversationReceiptHandler());
        ReceiptHandlerContainer.getInstance().registerMessageReceiptHandler(new CustomConversationReceiptHandler());
        //融云数据过滤器
        RongConfigCenter.conversationListConfig().setDataProcessor(new BaseDataProcessor<Conversation>() {
            @Override
            public Conversation.ConversationType[] supportedTypes() {
                //设置会话列表页支持的会话类型
                return supportedTypes;
            }

            @Override
            public List<Conversation> filtered(List<Conversation> data) {
                return data;
            }

            @Override
            public boolean isGathered(Conversation.ConversationType type) {
                return type.equals(Conversation.ConversationType.SYSTEM);
            }
        });

        //会话列表点击
        RongConfigCenter.conversationListConfig().setBehaviorListener(new ConversationListBehaviorListener() {
            @Override
            public boolean onConversationPortraitClick(Context context, Conversation.ConversationType conversationType, String targetId) {
                if (ViewUtil.isFastDoubleClick()) {
                    return false;
                }
                //如果是群通知，点击头像进入群通知页面
                if ("__group_apply__".equals(targetId)) {
                    return true;
                } else if ("0".equals(targetId)) {
                    RouterMessage.NotReplyMessageActivity(context.getString(R.string.no_reply_message));
                } else if (!MessageInfoUtil.isNeedFilter(targetId)) {
                    RouterUser.PersonalDetailActivity(targetId);
                    return true;
                }
                return false;
            }

            @Override
            public boolean onConversationPortraitLongClick(Context context, Conversation.ConversationType conversationType, String targetId) {
                return false;
            }

            @Override
            public boolean onConversationLongClick(Context context, View view, BaseUiConversation conversation) {
                return false;
            }

            @Override
            public boolean onConversationClick(Context context, View view, BaseUiConversation conversation) {
                // 未回复消息的监听
                if (conversation instanceof GatheredConversation && context.getString(R.string.rc_conversation_unreply_title).equals(conversation.mCore.getConversationTitle())) {
                    //当前把private设为了聚合，并起名标题为为回复消息
                    RouterMessage.NotReplyMessageActivity(conversation.mCore.getConversationTitle());
                } else {
                    String senderUserId = conversation.mCore.getSenderUserId();
                    if (MessageConstants.isSystemUser(senderUserId) || MessageConstants.isSystemUser(conversation.mCore.getTargetId())) {
                        RouterMessage.SystemMessageActivity(senderUserId, conversation.mCore.getConversationTitle(), conversation.mCore.getConversationType() == Conversation.ConversationType.PRIVATE ? 1 : 2);
                    } else {
                        int displayMode = 0;
                        RouterMessage.ConversationActivity(conversation.mCore.getTargetId(),
                                conversation.mCore.getConversationTitle(),
                                displayMode, conversation.mCore.getConversationType().getValue() == 3);
                        RxBus.getDefault().post(new MessageListRefreshEvent());
                    }
                }
                return true;
            }
        });

        //会话未读状态监听
        RongIMClient.getInstance().setSyncConversationReadStatusListener((conversationType, targetId) -> {
            RongIMClient.getInstance().getUnreadCount(new RongIMClient.ResultCallback<Integer>() {
                @Override
                public void onSuccess(Integer integer) {
                    RxBus.getDefault().post(new RongYunMessageUnreadStatusEvent(integer));
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {

                }
            }, Conversation.ConversationType.PRIVATE, Conversation.ConversationType.GROUP);


            RxBus.getDefault().post(new RongYunMessageChangeEvent());
        });

        // 配置聚合会话
        RongConfigCenter.gatheredConversationConfig().setConversationTitle(Conversation.ConversationType.PRIVATE, R.string.rc_conversation_unreply_title);
        RongConfigCenter.gatheredConversationConfig().setGatherConversationPortrait(Conversation.ConversationType.PRIVATE, getDrawableUri(R.mipmap.icon_news_weidu));
    }

    private Uri getDrawableUri(@DrawableRes int resId) {
        Resources resources = context.getResources();
        return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
                resources.getResourcePackageName(resId) + '/' +
                resources.getResourceTypeName(resId) + '/' +
                resources.getResourceEntryName(resId));
    }

    /**
     * 初始化会话相关
     */
    private void initConversation() {

        //消息模板中的点击
        RongIM.setConversationClickListener(new ConversationClickListener() {
            @Override
            public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo user, String targetId) {
                RouterUser.PersonalDetailActivity(user.getUserId(), "私聊");
                return false;
            }

            @Override
            public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo user, String targetId) {
                return false;
            }

            @Override
            public boolean onMessageClick(Context context, View view, Message message) {
                return false;
            }

            @Override
            public boolean onMessageLinkClick(Context context, String link, Message message) {
                return false;
            }

            @Override
            public boolean onReadReceiptStateClick(Context context, Message message) {
                return false;
            }

            @Override
            public boolean onMessageLongClick(Context context, View view, Message message) {
                return false;
            }
        });
    }

    /**
     * 注册消息及消息模版
     */
    private void initMessageAndTemplate() {
        List<Class<? extends MessageContent>> myMessages = new ArrayList<>();
        myMessages.add(RxAgoraCallMessageContent.class);
        myMessages.add(RXGiftMessageContent.class);
        myMessages.add(RXOfficeNoticeMessageContent.class);
        myMessages.add(BroadcastMessageContent.class);
        myMessages.add(ChatRoomMessageContent.class);
        myMessages.add(RXChatRoomGiftContent.class);
        myMessages.add(RXChatRoomNoticeFensContent.class);
        myMessages.add(HQVoiceMessage.class);
        myMessages.add(RXCustomTipMessageContent.class);
        myMessages.add(RXLongTipMessageContent.class);
        myMessages.add(RXShowTipMessageContent.class);
        myMessages.add(RXSystemPublishContent.class);
        myMessages.add(RXDiceMessageContent.class);
        myMessages.add(RXJoinGameContent.class);
        myMessages.add(RXGameContent.class);
        myMessages.add(RXRedPkgMessageContent.class);
        myMessages.add(RXShareMessageContent.class);
        myMessages.add(RedPackageTipMessageContent.class);
        myMessages.add(RXCreateGroupContent.class);
        myMessages.add(RXGroupKickContent.class);
        myMessages.add(RXGroupQuitContent.class);
        myMessages.add(RXGroupEditContent.class);
        myMessages.add(RXGroupJoinContent.class);
        myMessages.add(RXGameMessageContent.class);
        RongIMClient.registerMessageType(myMessages);

        // TODO: 2023/12/18 这里要添加消息类型
        RongIM.registerMessageTemplate(new RxAgoraCallMessageProvider()); //通话消息
        RongIM.registerMessageTemplate(new RXCustomTipMessageItemProvider()); //自定义tip消息
        RongIM.registerMessageTemplate(new RXShowTipMessageItemProvider()); //无背景消息模板
        RongIM.registerMessageTemplate(new RXDiceMessageItemProvider()); //骰子
        RongIM.registerMessageTemplate(new RXRedPkgMessageItemProvider()); //红包
        RongIM.registerMessageTemplate(new RXShareMessageItemProvider()); //分享
        RongIM.registerMessageTemplate(new RXGiftMessageItemProvider()); //私聊礼物消息
        RongIM.registerMessageTemplate(new RedPackageTipMessageItemProvider()); //红包领取的消息
        RongIM.registerMessageTemplate(new RXCreateGroupMessageItemProvider()); //创建群聊私信
        RongIM.registerMessageTemplate(new RXGroupKickMessageItemProvider()); //踢出群聊的消息
        RongIM.registerMessageTemplate(new RXGroupEditMessageItemProvider()); //群名称修改
        RongIM.registerMessageTemplate(new RXGroupJoinMessageItemProvider()); //群加入
        RongIM.registerMessageTemplate(new RXGroupQuitMessageItemProvider()); //退出群聊的消息

        //除了基础的几个，别的其实也不需要阅后即焚,

        //替换内置provide------------
        //替换文本消息
        RongConfigCenter.conversationConfig().replaceMessageProvider(TextMessageItemProvider.class, new CustomTextMessageItemProvider());
        //替换图片消息
        RongConfigCenter.conversationConfig().replaceMessageProvider(ImageMessageItemProvider.class, new CustomImageMessageItemProvider());
        //替换HQ语音消息-高清语音
        RongConfigCenter.conversationConfig().replaceMessageProvider(HQVoiceMessageItemProvider.class, new RxHQVoiceMessageItemProvider());
        //替换Gif图片
        RongConfigCenter.conversationConfig().replaceMessageProvider(GIFMessageItemProvider.class, new CustomGIFMessageItemProvider());
        //替换灰条通知
        RongConfigCenter.conversationConfig().replaceMessageProvider(InformationNotificationMessageItemProvider.class, new RXInformationNotificationMessageItemProvider());

        //替换会话列表模板
        ProviderManager<BaseUiConversation> providerManager = RongConfigCenter.conversationListConfig().getProviderManager(); //获取会话模板管理器
        CustomConversationProvider customConversationProvider = new CustomConversationProvider();
        providerManager.replaceProvider(PrivateConversationProvider.class, customConversationProvider);
        providerManager.setDefaultProvider(customConversationProvider);

        //data为null的情况下默认的走的provider，kit里面设置的是不支持的模板，这里设置为空页面
        RongConfigCenter.conversationConfig().getMessageListProvider().setDefaultProvider(new IViewProvider() {

            @Override
            public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View view = new View(parent.getContext());
                return new ViewHolder(parent.getContext(), view);
            }

            @Override
            public boolean isItemViewType(Object item) {
                return true;
            }

            @Override
            public void bindViewHolder(ViewHolder holder, Object o, int position, List list, IViewProviderListener listener) {
            }
        });
    }

    /**
     * 初始化连接状态监听
     */
    private void initConnectStateChangeListener() {
        IMCenter.getInstance().addConnectionStatusListener(connectionStatus -> {
            switch (connectionStatus) {
                case NETWORK_UNAVAILABLE:
                    break;
                case CONNECTING://连接中 CONNECTING CONNECTED SUSPEND
                    TLogManager.loge(TAG_MODULE, TAG, "RongYunLogin - 融云链接状态 - CONNECTING = 连接中");
                    break;
                case UNCONNECTED:// 断开链接
                    TLogManager.loge(TAG_MODULE, TAG, "RongYunLogin - 融云链接状态 - UNCONNECTED = 断开链接");
                    break;
                case CONNECTED://成功
                    TLogManager.loge(TAG_MODULE, TAG, "RongYunLogin - 融云链接状态 - CONNECTED = 链接成功");
                    RxBus.getDefault().post(new RongYunLoginSuccessEvent());
                    break;
                case KICKED_OFFLINE_BY_OTHER_CLIENT://用户账户在其他设备登录，本机会被踢掉线。
                    TLogManager.loge(TAG_MODULE, TAG, "RongYunLogin - 融云链接状态 - KICKED_OFFLINE_BY_OTHER_CLIENT = 用户账户在其他设备登录，本机会被踢掉线");
                    ToastUtil.showMessage(context.getString(R.string.your_account_has_login_in_other_device));
                    RxBus.getDefault().post(new ExitAppEvent());
                    break;
                case TOKEN_INCORRECT:
                    TLogManager.loge(TAG_MODULE, TAG, "RongYunLogin - 融云链接状态 - TOKEN_INCORRECT = Token过期");
                    break;
                case CONN_USER_BLOCKED:
                    TLogManager.loge(TAG_MODULE, TAG, "RongYunLogin - 融云链接状态 - CONN_USER_BLOCKED = 连接被阻止");
                    break;
                default:
                    break;
            }
        });
    }

    /**
     * 初始化消息监听
     */
    private void initOnReceiveMessage(Context context) {
        RongConfigCenter.conversationConfig().setSupportReadReceiptConversationType(
                Conversation.ConversationType.PRIVATE,
                Conversation.ConversationType.CHATROOM,
                Conversation.ConversationType.GROUP);
        IMCenter.getInstance().addOnReceiveMessageListener(new RongIMClient.OnReceiveMessageWrapperListener() {
            @Override
            public boolean onReceived(Message message, int i, boolean hasPackage, boolean isOffline) {
                Log.i("gz-ryMsg", "receive a message!!!");
                Log.i("gz-ryMsg", "msg name=>" + message.getObjectName() + "\t\t\t messageContent:" + message.getContent());
                long sentTime = message.getSentTime();
                long receivedTime = message.getReceivedTime();
                Log.i("gz-ryMsg", "sentTime:" + TimeUtils.millis2String(sentTime));
                Log.i("gz-ryMsg", "receivedTime:" + TimeUtils.millis2String(receivedTime));
                try {
                    //去掉由于多端登录重复获取的消息。
                    if (isOffline && message != null && message.getReceivedStatus() != null && message.getReceivedStatus().isRetrieved()) {
                        Log.i("gz-ryMsg", "去掉一条离线已读消息");
                        return true;
                    }
                } catch (Exception e) {
                    Log.e("gz-error", "RongYunManage :: errorMsg =" + e.getMessage());
                }

                return doReceivedMsg(message, context, false);
            }
        });

        IMCenter.getInstance().addOnReceiveMessageListener(new RongIMClient.OnReceiveMessageWrapperListener() {
            @Override
            public boolean onReceived(Message message, int i, boolean hasPackage, boolean isOffline) {
                //每次都用新的对象传入，否则可能有草稿影响消息内容显示
                if (message.getConversationType().equals(Conversation.ConversationType.PRIVATE)
                        && RXingUtils.getPersonDetail() != null
                        && !isOffline
                        && !message.getSenderUserId().equals(RXingUtils.getPersonDetail().getBasic().getUserId())) {

                    UserInfo userInfo = RongUserInfoManager.getInstance().getUserInfo(message.getTargetId());

                    if (null != userInfo) {
                        Conversation obtain = Conversation.obtain(message.getConversationType(), message.getTargetId(), userInfo.getName());
                        obtain.setLatestMessage(message.getContent());
                        obtain.setSenderUserId(message.getSenderUserId());
                        obtain.setReceivedTime(message.getReceivedTime());
                        obtain.setSentTime(message.getSentTime());
                        obtain.setPortraitUrl(userInfo.getPortraitUri().getPath());
                        obtain.setLatestMessageId(message.getMessageId());

                        BaseUiConversation uiConversation = new SingleConversation(context, obtain);
                        // 加载飘屏消息
                        MsgFloatDialogHelper.getInstance().showFloatDialog(context, uiConversation);
                    }
                }
                return false;
            }
        });
    }

    /**
     * 消息解析
     */
    public static boolean doReceivedMsg(Message message, Context mApplication, boolean isEnterChatRoom) {
        try {
            LogDataUtils.d("rongyun_message_doReceivedMsg", message.toString() + " messageObjectName: " + message.getObjectName());

            long deltaTime = RongIM.getInstance().getDeltaTime();
            long rTimes = message.getReceivedTime() - message.getSentTime() - deltaTime;
            if (isEnterChatRoom) {
                rTimes = 5000;
            }
            if (message.getObjectName().equals(IMMessageType.INFO_NTF_MESSAGE)) {
                InformationNotificationMessage mInformationNotificationMessage = (InformationNotificationMessage) (message.getContent());
                Log.d("gz-ryMsg", mInformationNotificationMessage.getExtra());
                JSONObject jsonObject = JSONObject.parseObject(mInformationNotificationMessage.getExtra());
                String type = jsonObject.getString("type");
                if ("intimateInfo".equals(type)) {
                    Log.e("gz-ryMsg", "亲密礼物：intimateInfo == " + jsonObject);
                    String[] giftIds = jsonObject.getString("messageId").split(",");
                    for (String giftId : giftIds) {
                        Log.e("gz-ryMsg", "亲密礼物：giftId == " + giftId);
                        RongIMClient.getInstance().getMessageByUid(giftId, new RongIMClient.ResultCallback<Message>() {
                            @Override
                            public void onSuccess(Message message) {
                                Log.e("gz-ryMsg", "亲密礼物：message == " + message);
                                if (message == null) {
                                    return;
                                }
                                RongIMClient.getInstance().setMessageExtra(message.getMessageId(), "1", new RongIMClient.ResultCallback<Boolean>() {
                                    @Override
                                    public void onSuccess(Boolean aBoolean) {
                                        Log.e("gz-ryMsg", "亲密礼物:setMessageExtra aBoolean == " + aBoolean);
                                    }

                                    @Override
                                    public void onError(RongIMClient.ErrorCode errorCode) {
                                        Log.e("gz-ryMsg", "亲密礼物:setMessageExtra errorCode == " + errorCode);
                                    }
                                });
                            }

                            @Override
                            public void onError(RongIMClient.ErrorCode errorCode) {

                            }
                        });
                    }
                }
            } else if (message.getObjectName().equals(IMMessageType.SERVER_NOTICE_MESSAGE)) {
                Log.e("gz-ryMsg", "=>收到Agora来电=>msg=>" + message);
                MessageContent messageContent = message.getContent();
                RXOfficeNoticeMessageContent mRXAssistantMessageContent = (RXOfficeNoticeMessageContent) (messageContent);

                CustomAttachEvent mCustomeAttachEvent = new CustomAttachEvent(mRXAssistantMessageContent.getType(), mRXAssistantMessageContent.getData());
                Log.d("gz-ryMsg", "getType: " + mCustomeAttachEvent.getType() + "data: " + mCustomeAttachEvent.getData());
                switch (mCustomeAttachEvent.getType()) {
                    case 25:
                        //声网来电
                        AgoraCallMsg callMsg = JSON.parseObject(mRXAssistantMessageContent.getData(), AgoraCallMsg.class);
                        callMsg.setLocalCallTime(System.currentTimeMillis());

                        TLogManager.loge(TAG_MODULE1, TAG, "doReceivedMsg - 接收到声网来电的消息 - 通道名 = " + callMsg.getChannelName()
                                + " --- 消息状态 = " + (callMsg.getStatus() == 1 ? "接听" : "挂断")
                                + " --- json内容 = " + mRXAssistantMessageContent.getData());

                        // 解析消息对象 -  创建声网广播事件 - 传递到MainActivity
                        RxBus.getDefault().post(new AgoraCallEvent(callMsg));
                        Log.e("tag--", "AgoreCallEvent----电话通话" + callMsg.getStatus());
                        Log.d("gz-ryMsg", "Agora-call:: topactivity=>" + ActivityManagerUtils.getInstance().getTopActivity() + " ");
                        RongYunNotifyHelper.IncomeCallNotify(mApplication.getApplicationContext(), callMsg);
                        break;
                    case 26:
                        //消息发送失败/被拦截
                        InterceptMsg msg = JSON.parseObject(mRXAssistantMessageContent.getData(), InterceptMsg.class);
                        if (msg != null) {
                            if (!TextUtils.isEmpty(msg.getContent())) {
                                ToastUtil.showMessage(msg.getContent());
                            }
                        }
                        break;
                    default:
                        RxBus.getDefault().post(mCustomeAttachEvent);
                        break;
                }
            } else if (message.getObjectName().equals(IMMessageType.BROAD_CAST_MESSAGE)) {
                MessageContent messageContent = message.getContent();
                BroadcastMessageContent mBroadcastMessageContent = (BroadcastMessageContent) (messageContent);
                TLogManager.logi("manager", TAG, "RY mBroadcastMessageContent: %s, extra: %s, timelines: %d", mBroadcastMessageContent.getContent(), mBroadcastMessageContent.getExtra(), rTimes);
                BroadCastType mBroadCastType = JSON.parseObject(mBroadcastMessageContent.getExtra(), BroadCastType.class);

            } else if (message.getObjectName().equals(IMMessageType.GIFT_MESSAGE)) {
                //礼物信息
                EventBus.getDefault().post(new GiftIconEvent());
                long timeLeft = (System.currentTimeMillis() - message.getSentTime()) / 1000;
                if (timeLeft > 5 * 60) {
                    message.setExtra("2");
                } else {
                    message.setExtra("0");
                }
            } else if (message.getObjectName().equals(IMMessageType.DICE_MESSAGE)) {
                //骰子
                EventBus.getDefault().post(new GiftIconEvent());
            } else if (message.getObjectName().equals(IMMessageType.TEXT_MESSAGE)) {
                if (message.getConversationType().equals(Conversation.ConversationType.CHATROOM)) {
                    //聊天室消息
                    MessageContent messageContent = message.getContent();
                    TextMessage mTextMessage = (TextMessage) (messageContent);
                    Log.e("", "IreneBond chatRoom content: " + mTextMessage.getContent() + " extra: " + mTextMessage.getExtra());
                    RongYunOnReceiverMsgManager.getInstance().spreadChatRoomMessage(new ChatRoomMessage(ChatRoomMsgType.TYPE_SIMPLE_TEXT,
                            message.getMessageId(), mTextMessage.getContent(), mTextMessage.getExtra(), rTimes, message.getTargetId()));
                }
            } else if (message.getObjectName().equals(IMMessageType.IMAGE_MESSAGE)) {
                if (message.getConversationType().equals(Conversation.ConversationType.CHATROOM)) {
                    //聊天室消息
                    MessageContent messageContent = message.getContent();
                    ImageMessage mTextMessage = (ImageMessage) (messageContent);
                    Log.e("", "IreneBond chatRoom content: " + mTextMessage + " extra: " + mTextMessage.getExtra());
                    RongYunOnReceiverMsgManager.getInstance().spreadChatRoomMessage(new ChatRoomMessage(ChatRoomMsgType.TYPE_PHOTO,
                            message.getMessageId(), mTextMessage.getRemoteUri().toString(), mTextMessage.getExtra(), rTimes, message.getTargetId()));
                }
            } else if (message.getObjectName().equals(IMMessageType.CHAT_ROOM_GIFT_MSG)) {
                MessageContent messageContent = message.getContent();
                RXChatRoomGiftContent mRXChatRoomGiftContent = (RXChatRoomGiftContent) (messageContent);
                String ext = mRXChatRoomGiftContent.getExt();
                LogDataUtils.d("rongyun_message_1", mRXChatRoomGiftContent.getContent() + " extra: " + mRXChatRoomGiftContent.getExtra() + " ext: "
                        + mRXChatRoomGiftContent.getExt());
                ChatRoomGiftDetail giftDetail = JSON.parseObject(mRXChatRoomGiftContent.getExt(), ChatRoomGiftDetail.class);
                if (giftDetail.getType().equals(IMMessageType.TYPE_CHAT_ROOM_SEND_GIFT)) {
                    RongYunOnReceiverMsgManager.getInstance().spreadChatRoomMessage(new ChatRoomMessage(
                            ChatRoomMsgType.TYPE_CHATROOM_GIFT,
                            message.getMessageId(), mRXChatRoomGiftContent.getExt(), mRXChatRoomGiftContent.getExtra(), rTimes, message.getTargetId()));
                }
                if (rTimes < 2000 &&
                        (giftDetail.getType().equals(IMMessageType.TYPE_CHAT_ROOM_SEND_GIFT))) {

                    if (giftDetail.getType().equals(IMMessageType.TYPE_CHAT_ROOM_SEND_GIFT)) {
                        if (ext.contains("isShowEffect")) {
                            if (giftDetail.getIsShowEffect() == 1) {
                                RxBus.getDefault().post(new ShowGiftFullScreenAnimEvent(giftDetail.getGiftId(), giftDetail.getGift(),
                                        giftDetail.getGifUrl(), giftDetail.getSpeContent(),
                                        giftDetail.getSvgaImage(), giftDetail.getMp4(),
                                        giftDetail.getFromNick(),
                                        giftDetail.getAvatar(), giftDetail.getToNick(),
                                        giftDetail.getGiftIcon(), giftDetail.getUnit(),
                                        giftDetail.getNum(), giftDetail.getWorth(),
                                        giftDetail.getSound_file(), giftDetail.getSvgaConfig(),
                                        giftDetail.getDynamicEffect(), giftDetail.getReceiverUids(),
                                        giftDetail.getFromUidString()));
                            }
                        } else {
                            RxBus.getDefault().post(new ShowGiftFullScreenAnimEvent(giftDetail.getGiftId(), giftDetail.getGift(),
                                    giftDetail.getGifUrl(), giftDetail.getSpeContent(),
                                    giftDetail.getSvgaImage(), giftDetail.getMp4(),
                                    giftDetail.getFromNick(),
                                    giftDetail.getAvatar(), giftDetail.getToNick(),
                                    giftDetail.getGiftIcon(), giftDetail.getUnit(),
                                    giftDetail.getNum(), giftDetail.getWorth(),
                                    giftDetail.getSound_file(), giftDetail.getSvgaConfig(),
                                    giftDetail.getDynamicEffect(), giftDetail.getReceiverUids(),
                                    giftDetail.getFromUidString()));
                        }
                    }
                }
            } else if (message.getObjectName().equals(IMMessageType.TYPE_CHAT_ROOM_NOTICE_FENS_MSG)) {
                MessageContent messageContent = message.getContent();
                RXChatRoomNoticeFensContent mRXChatRoomNoticeFensContent = (RXChatRoomNoticeFensContent) (messageContent);
                RongYunNotifyHelper.JoinChatRoomNotify(mApplication.getApplicationContext(), mRXChatRoomNoticeFensContent.getRoom_id(), mRXChatRoomNoticeFensContent.getText());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 初始化聊天室监听
     */
//    public void initChatRoomActionListener() {
//        RongChatRoomClient.setChatRoomAdvancedActionListener(new RongChatRoomClient.ChatRoomAdvancedActionListener() {
//            @Override
//            public void onJoining(String roomId) {
//                chatRoomActionLiveData.postValue(ChatRoomAction.joining(roomId));
//            }
//
//            @Override
//            public void onJoined(String roomId) {
//                chatRoomActionLiveData.postValue(ChatRoomAction.joined(roomId));
//            }
//
//            @Override
//            public void onReset(String roomId) {
//                chatRoomActionLiveData.postValue(ChatRoomAction.reset(roomId));
//            }
//
//            @Override
//            public void onQuited(String roomId) {
//                chatRoomActionLiveData.postValue(ChatRoomAction.quited(roomId));
//            }
//
//            @Override
//            public void onDestroyed(String chatRoomId, IRongCoreEnum.ChatRoomDestroyType type) {
//                chatRoomActionLiveData.postValue(ChatRoomAction.destroyed(chatRoomId));
//            }
//
//            @Override
//            public void onError(String chatRoomId, IRongCoreEnum.CoreErrorCode code) {
//                chatRoomActionLiveData.postValue(ChatRoomAction.error(chatRoomId));
//            }
//        });
//    }

    private String lastLoginToken;

    /**
     * 缓存登录
     */
    public void cacheConnectIM() {

        UserLoginInfo loginAccount = RXingUtils.getLoginAccount();
        String loginToken = loginAccount.getUserInfo().getRongappid();

        if (RongIMClient.getInstance().getCurrentConnectionStatus() == RongIMClient.ConnectionStatusListener.ConnectionStatus.CONNECTED && TextUtils.equals(lastLoginToken, loginToken)) {
            autoLoginResult.setValue(true);
            return;
        }

        if (RongIMClient.getInstance().getCurrentConnectionStatus() == RongIMClient.ConnectionStatusListener.ConnectionStatus.CONNECTING) {
            return;
        }

        connectIM(loginToken, true, new ResultCallback<String>() {
            @Override
            public void onSuccess(String s) {
                lastLoginToken = loginToken;
                autoLoginResult.postValue(true);
            }

            @Override
            public void onFail(int errorCode) {
                // 缓存登录时可以认为缓存了之前连接成功过的结果，所以当再次连接失败时可以通过 SDK 自动重连连接成功
                autoLoginResult.postValue(true);
            }
        });
    }

    /**
     * 如果IMtoken为空，那么我再次请求token进行登录
     */
    public void getIMToken() {
        BizLayer.getInstance().getAccountModule().getIMToken(new AresSubscriber<UserLoginInfo>() {
            @Override
            protected void onSuccess(UserLoginInfo info) {
                if (info != null && info.getRongToken() != null) {
                    UserLoginInfo loginAccount = RXingUtils.getLoginAccount();
                    loginAccount.getUserInfo().setRongappid(info.getRongToken());
                    RXingUtils.saveLoginAccount(loginAccount);
                    cacheConnectIM();
                }
            }

            @Override
            protected void onError(int code, String info) {
                autoLoginResult.setValue(false);
            }
        });
    }

    /**
     * 连接 IM 服务
     *
     * @param autoConnect 是否在连接失败时无限时间自动重连
     */
    public void connectIM(String token, boolean autoConnect, ResultCallback<String> callback) {
        if (autoConnect) {
            connectIM(token, 0, callback);
        } else {
            connectIM(token, 10, callback);
        }
    }

    /**
     * 连接 IM 服务
     *
     * @param timeOut 自动重连超时时间。
     */
    public void connectIM(String token, int timeOut, ResultCallback<String> callback) {
        /*
         *  考虑到会有后台调用此方法，所以不采用 LiveData 做返回值
         */
        IMCenter.getInstance().connect(token, timeOut, new RongIMClient.ConnectCallback() {
            @Override
            public void onSuccess(String userId) {
                // 连接 IM 成功后，初始化数据库
                SystemConfigBean systemConfig = AppConfigCacheManager.getInstance().getSystemConfig();
                if (systemConfig == null) {
                    return;
                }
                String roomId = systemConfig.getOnlineChatRoomId();
                RongIMClient.getInstance().joinChatRoom(roomId, -1, new RongIMClient.OperationCallback() {
                    @Override
                    public void onSuccess() {
                        Log.d("gz-rymsg", "IreneBond 加入聊天室成功：" + roomId);
                        TLogManager.loge(TAG_MODULE1, TAG, "connectIM - 加入聊天室成功 - roomId = " + roomId);
                        RxBus.getDefault().post(new RongYunLoginSuccessEvent());
                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {
                        TLogManager.loge(TAG_MODULE1, TAG, "connectIM - 加入聊天室失败  = " + errorCode);
                    }
                });

                TLogManager.loge(TAG_MODULE1, TAG, "connectIM - 登陆成功 - userid = " + userId);
                if (callback != null) {
                    callback.onSuccess(token);
                }
                Log.d("gz-rymsg", "RYLogin-登陆成功:: userid =>" + userId);
            }

            @Override
            public void onError(RongIMClient.ConnectionErrorCode connectionErrorCode) {

                RxBus.getDefault().post(new RongYunExceptionEvent(connectionErrorCode.getValue()));

                if (connectionErrorCode.equals(RongIMClient.ConnectionErrorCode.RC_CONN_TOKEN_INCORRECT)) {
                    //从 APP 服务获取新 token，并重连
                    TLogManager.loge(TAG_MODULE1, TAG, "connectIM - 登陆失败  = ：融云登陆的token不正确");
                } else {
                    TLogManager.loge(TAG_MODULE1, TAG, "connectIM - 登陆失败  = " + connectionErrorCode);
                }
            }

            @Override
            public void onDatabaseOpened(RongIMClient.DatabaseOpenStatus databaseOpenStatus) {

            }
        });
    }

    /**
     * 清理未读消息状态
     *
     * @param conversationTypes 指定清理的会话类型
     */
    public void clearMessageUnreadStatus(Conversation.ConversationType[] conversationTypes) {
        RongIMClient.getInstance().getConversationList(new RongIMClient.ResultCallback<List<Conversation>>() {
            @Override
            public void onSuccess(List<Conversation> conversations) {
                if (conversations != null && conversations.size() > 0) {
                    for (Conversation c : conversations) {
                        clearMessageUnreadStatus(c);
                    }
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode e) {

            }
        }, conversationTypes);
    }

    /**
     * 清理未读消息状态
     *
     * @param c 指定清理的会话
     */
    public void clearMessageUnreadStatus(Conversation c) {
        IMCenter.getInstance().clearMessagesUnreadStatus(c.getConversationType(), c.getTargetId(), null);
        if (c.getConversationType() == Conversation.ConversationType.PRIVATE || c.getConversationType() == Conversation.ConversationType.GROUP || c.getConversationType() == Conversation.ConversationType.ENCRYPTED) {
            RongIMClient.getInstance().sendReadReceiptMessage(c.getConversationType(), c.getTargetId(), c.getSentTime(), new IRongCallback.ISendMessageCallback() {

                @Override
                public void onAttached(Message message) {

                }

                @Override
                public void onSuccess(Message message) {

                }

                @Override
                public void onError(Message message, RongIMClient.ErrorCode errorCode) {

                }
            });
        }
        RongIMClient.getInstance().syncConversationReadStatus(c.getConversationType(), c.getTargetId(), c.getSentTime(), null);
    }

    /**
     * 清除会话及消息
     */
    public void clearConversationAndMessage(String targetId, Conversation.ConversationType conversationType) {
        RongIMClient.getInstance().getConversation(conversationType, targetId, new RongIMClient.ResultCallback<Conversation>() {
            @Override
            public void onSuccess(Conversation conversation) {
                IMCenter.getInstance().cleanHistoryMessages(conversationType, targetId, 0, false, new RongIMClient.OperationCallback() {
                    @Override
                    public void onSuccess() {
                        IMCenter.getInstance().removeConversation(conversationType, targetId, new RongIMClient.ResultCallback<Boolean>() {
                            @Override
                            public void onSuccess(Boolean aBoolean) {

                            }

                            @Override
                            public void onError(RongIMClient.ErrorCode errorCode) {

                            }
                        });
                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {

                    }
                });
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        });
    }

    /**
     * 删除指定会话类型所有消息
     *
     * @param conversationTypes 指定删除的会话类型
     */
    public void deleteMessage(Conversation.ConversationType[] conversationTypes) {
        RongIMClient.getInstance().getConversationList(new RongIMClient.ResultCallback<List<Conversation>>() {
            @Override
            public void onSuccess(List<Conversation> conversations) {
                if (conversations != null && conversations.size() > 0) {
                    for (Conversation c : conversations) {
                        IMCenter.getInstance().deleteMessages(c.getConversationType(), c.getTargetId(), null);
                        IMCenter.getInstance().removeConversation(c.getConversationType(), c.getTargetId(), null);
                        //删除远端消息
                        RongIMClient.getInstance().cleanRemoteHistoryMessages(c.getConversationType(), c.getTargetId(), 0, null);
                        //由于业务需求，下次安装的消息是根据已读状态删除的，所有这里也要清空未读数量
                        clearMessageUnreadStatus(c);
                    }
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode e) {

            }
        }, conversationTypes);
    }

    /**
     * 删除已读的所有消息
     *
     * @param conversationTypes 指定删除的会话类型
     */
    public void deleteReadMessage(Conversation.ConversationType[] conversationTypes) {
        RongIMClient.getInstance().getConversationList(new RongIMClient.ResultCallback<List<Conversation>>() {
            @Override
            public void onSuccess(List<Conversation> conversations) {
                if (conversations != null && conversations.size() > 0) {
                    for (Conversation c : conversations) {
                        if (c.getUnreadMessageCount() == 0) {
                            IMCenter.getInstance().deleteMessages(c.getConversationType(), c.getTargetId(), null);
                            IMCenter.getInstance().removeConversation(c.getConversationType(), c.getTargetId(), null);
                            //删除远端消息
                            RongIMClient.getInstance().cleanRemoteHistoryMessages(c.getConversationType(), c.getTargetId(), 0, null);
                            //由于业务需求，下次安装的消息是根据已读状态删除的，所有这里也要清空未读数量
                            clearMessageUnreadStatus(c);
                        }
                    }
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode e) {

            }
        }, conversationTypes);
    }

    /**
     * 更新 IMKit 显示用用户信息
     */
    public void updateUserInfoCache(String userId, String userName, Uri portraitUri) {
        UserInfo oldUserInfo = RongUserInfoManager.getInstance().getUserInfo(userId);
        if (oldUserInfo == null
                || (!oldUserInfo.getName().equals(userName)
                || oldUserInfo.getPortraitUri() == null
                || !oldUserInfo.getPortraitUri().equals(portraitUri))
        ) {
            UserInfo userInfo = new UserInfo(userId, userName != null ? userName : "", portraitUri);
            RongUserInfoManager.getInstance().setCurrentUserInfo(userInfo);
            RongUserInfoManager.getInstance().refreshUserInfoCache(userInfo);
            Log.e("wang", "refreshUserInfoCache----->" + JSONObject.toJSONString(userInfo));
        }
    }
}